﻿<%
class ActionMedia
	private System
	private sub Class_Initialize()
		if F.session("wx_auth_name")="" then
			F.redirect "?m=login&msg=" & F.encode("请登录。")
		else
			dim L : set L = Model__("System","Id").where("Tag=1").query().fetch()
			if L.Eof() then
				F.redirect "?m=Admin&error=1&msg=" & F.encode("找不到微信配置。")
			else
				set System = L.Read()
				Mo.assign "WxSrcId",System.Wx_Acount_SrcId
				Mo.assign "System",System
				Mo.assign "subtitle","素材管理"
			end if
		end if
	end sub
	public sub index
		dim sqlwhere:sqlwhere=""
		if F.get.safe("MediaId")<>"" then sqlwhere = sqlwhere & "MediaId='" & F.get.safe("MediaId") & "'"
		Model__("Media","Id").where(sqlwhere).limit(F.get.int("page",1),10).orderby("CreatedAt desc").query().assign "Media"
		Mo.assign "now",F.timespan()-3600*24*3
		Mo.display "Admin:Media"
	end sub
	public sub download
		Mo.Use "WXServices"
		dim WX,json : set WX = MoLibWXServices.New(System.AppID,System.AppSecret)
		if WX.getAccessToken() then
			dim MediaId:MediaId = F.get.safe("MediaId")
			set json = WX.downloadmedia(MediaId)
			if json.error then
				F.goto "?m=Media&error=1&msg=" & F.encode(WX.errmsg)
			else
				Response.ContentType = json.contenttype
				Response.AddHeader "Content-disposition",json.filename
				F.echo json.data,F.TEXT.BIN
			end if
		else
			F.goto "?m=Media&error=1&msg=" & F.encode("无法获取AccessToken。" & WX.errmsg)
		end if
	end sub
	public sub delete
		dim id,M,path:id = F.get.int("Id",0)
		set M = Model__("Media","Id").where("Id=" & id).query()
		path = M.fetch().Read("LocalPath")
		if not is_empty(path) then
			if not(F.string.startWith(lcase(path),"http://") or F.string.startWith(lcase(path),"https://")) then
				if F.fso.fileexists(F.mappath(path)) then F.fso.deletefile F.mappath(path)
			end if
		end if
		M.delete()
		F.goto "?m=Media&error=0&msg=" & F.encode("操作成功")
	end sub
	public sub rename
		dim id:id = F.post.int("Id",0)
		dim name:name = F.post.safe("Name")
		if name<>F.post("Name") then
			F.echo "1,名称含有非法字符。"
			exit sub
		end if
		if len(name)>30 then
			F.echo "1,名称不能超过30个字符。"
			exit sub
		end if
		Model__("Media","Id").where("Id=" & id).update "Name",name
		if Model__.lastRows>0 then
			F.echo "0,保存成功。"
		else
			F.echo "1,保存失败。"
		end if
	end sub
	public sub upload2wx
		Mo.Use "WXServices"
		dim WX : set WX = MoLibWXServices.New(System.AppID,System.AppSecret)
		if WX.getAccessToken() then
			dim id:id = F.get.int("Id",0)
			if id>0 then
				dim L:set L = Model__("Media","Id").where("Id=" & id).query().fetch()
				if L.Eof() then
					F.goto "?m=Media&page=" & F.get.int("page",1) & "&error=1&msg=" & F.encode("记录不存在。")
				else
					dim R:set R =L.Read()
					LocalPath = R.LocalPath
					dim contenttype:contenttype="application/octet-stream"
					if R.Type="image" or R.Type="thumb" then contenttype="Image/Jpeg"
					if F.string.startWith(lcase(R.LocalPath),"http://") or F.string.startWith(lcase(R.LocalPath),"https://") then
						Mo.Use "HttpRequest"
						dim httprequest,LocalPath,ext:set httprequest = MoLibHttpRequest.New(R.LocalPath).send()
						if R.Type="image" then ext=".jpg"
						if R.Type="voice" then ext=".mp3"
						if R.Type="video" then ext=".mp4"
						if R.Type="thumb" then ext=".jpg"
						if httprequest.status=200 then
							LocalPath = "Contents/Medias/" & R.Type & "/" & F.formatdate(now(),"yyyyMMddHHmmss") & Rndstr(4) & ext
							httprequest.saveToFile F.mappath(LocalPath)
							Model__("Media","Id").where("Id=" & id).update "LocalPath",LocalPath,"CreatedAt",F.timespan()
						else
							LocalPath=""
						end if
					end if
					if not F.fso.fileexists(F.mappath(LocalPath)) then
						F.goto "?m=Media&page=" & F.get.int("page",1) & "&error=1&msg=" & F.encode("文件不存在")
					else
						dim json:set json = WX.upload(R.Type,F.mappath(LocalPath),contenttype)
						if json.error then
							F.goto "?m=Media&page=" & F.get.int("page",1) & "&error=1&msg=" & F.encode(WX.errmsg)
						else
							dim mediaid
							if R.Type="thumb" then mediaid = json.thumb_media_id else mediaid = json.media_id
							Model__("Media","Id").where("Id=" & id).update "MediaId",mediaid,"CreatedAt",json.created_at
							F.goto "?m=Media&page=" & F.get.int("page",1) & "&error=0&msg=" & F.encode("成功上传")
						end if
					end if
				end if
			else
				F.goto "?m=Media&page=" & F.get.int("page",1) & "&error=1&msg=" & F.encode("错误的Id。")
			end if
		else
			F.goto "?m=Media&page=" & F.get.int("page",1) & "&error=1&msg=" & F.encode("无法获取AccessToken。" & WX.errmsg)
		end if
	end sub
	public sub upload2
		dim Upload : set Upload = Mo("Upload")
		Upload.AllowFileTypes = "*.jpg;*.amr;*.mp3;*.mp4;"
		Upload.AllowMaxFileSize = "1MB"
		Upload.AllowMaxSize = "1mb"
		Upload.CharSet = "utf-8"
		if not Upload.GetData() then 
			F.goto "?m=Media&error=1&msg=" & F.encode(Upload.Description)
		else
			dim ty,name,MediaUrl
			ty = Upload.Post("Type")
			if ty="image" or ty="voice" or ty="video" or ty="thumb" then
				name = Upload.Post("Name")
				MediaUrl = Upload.Post("MediaUrl")
				Upload.SavePath = "Contents/Medias/" & ty
				Set File = Upload.Save("Media",0,true)
				if File.Succeed then
					if name ="" then name = replaceex(File.LocalName,"\.(.*?)$","")
					Model__("Media","Id").insert "Name",F.safe(name,20),"Type",ty,"LocalPath","Contents/Medias/" & ty & "/" & File.FileName,"CreatedAt",F.timespan()
					F.goto "?m=Media&error=0&msg=" & F.encode("媒体上传成功。")
				else
					if File.Exception="ERROR_FILE_NO_FOUND" and (F.string.startWith(lcase(MediaUrl),"http://") or F.string.startWith(lcase(MediaUrl),"https://")) then
						Mo.Use "HttpRequest"
						dim httprequest,LocalPath,ext:set httprequest = MoLibHttpRequest.New(MediaUrl).send()
						ext=""
						if instrrev(MediaUrl,".")>0 then ext = mid(MediaUrl,instrrev(MediaUrl,"."))
						if ext="" then
							if ty="image" then ext=".jpg"
							if ty="voice" then ext=".mp3"
							if ty="video" then ext=".mp4"
							if ty="thumb" then ext=".jpg"
						end if
						if httprequest.status=200 then
							LocalPath = "Contents/Medias/" & ty & "/" & F.formatdate(now(),"yyyyMMddHHmmss") & Rndstr(4) & ext
							httprequest.saveToFile F.mappath(LocalPath)
							if name ="" then name = replaceex(LocalPath,"^(.+)\/([^\/]+?)\.(.+?)$","$2")
							Model__("Media","Id").insert "Name",F.safe(name,20),"Type",ty,"LocalPath",LocalPath,"CreatedAt",F.timespan()
							F.goto "?m=Media&error=0&msg=" & F.encode("网络上传成功。")
						else
							F.goto "?m=Media&error=1&msg=" & F.encode("网络上传错误（" & httprequest.status & "）。")
						end if
					else
						F.goto "?m=Media&error=1&msg=" & F.encode(File.Exception)
					end if
				end if
			else
				F.goto "?m=Media&error=1&msg=" & F.encode("错误的媒体类型：" & ty)
			end if
		end if
		set Upload = nothing
	end sub
	public sub [empty](a)
		F.goto "?m=" & Mo.Method & "&error=1&msg=" & F.encode("不支持的方法：" & a & "。")
	end sub
end class
%>